﻿using System;
using System.Linq;
using System.Text;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Core.Security;
using System.Web.Security;
using Web.Core.Extensions;
using Web.Core.ActionResults;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extension;
using System.Web.Script.Serialization;

namespace Web.Core.Controllers
{
    public class GlobalController : CoreController
    {
        private const string SignInCaptchaKey = "signin";

        public GlobalController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }

        public void Index(UserRole param = UserRole.Buyer|UserRole.Seller|UserRole.Administrator)
        {
            SetAuthCookie("13718414243", false, new Identity(1, string.Empty, string.Empty, param));
        }

        public void Purge(string param)
        {
            Passport.Value.CachePurge();
        }

        public ActionResult Identity()
        {
            var sb = new StringBuilder();
            sb.Append("Ayatta.Identity={");
            sb.AppendFormat("Id:{0},", User.Identity.Identity().Id);
            sb.AppendFormat("Name:'{0}',", User.Identity.Name);
            sb.AppendFormat("NickName:'{0}',", User.Identity.Identity().Nickname);
            sb.AppendFormat("IsAuthenticated:{0}", User.Identity.IsAuthenticated.ToString().ToLower());
            sb.Append("};");
            return JavaScript(sb.ToString());
        }

        #region 登录
        /// <summary>
        /// 通用AJAX登录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult SignIn(string param)
        {
            return PartialView();
        }

        /// <summary>
        /// 通用AJAX登录
        /// </summary>
        /// <param name="username">用户名/绑定邮箱/绑定手机号码</param>
        /// <param name="password">登录密码</param>
        /// <param name="captcha">验证码</param>
        /// <param name="remember"></param>
        /// <param name="redirect">登录成功后跳转Url</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SignIn(string username, string password, string captcha, bool remember = false, string redirect = null)
        {
            var result = new MagicKit<string, string>();
            if (!CaptchaValidateInternal(SignInCaptchaKey, captcha))
            {
                result.Message = "请输入正确的验证码！";
                return Json(result);
            }
            var pwd = (password.HashPassword() + PasswordSalt).HashPassword();
            var user = Passport.Value.UserSignIn(username, pwd);
            if (user != null)
            {
                result.Status = true;
                result.Extra = redirect;
                result.Data = user.Nickname;
                var identity = new Identity(user.Id, user.Guid, user.Nickname, user.Role, user.Level, user.Limit,user.Permit, user.Avatar, user.Authenticated);
                SetAuthCookie(user.Name, remember, identity);
            }
            else
            {
                result.Message = "用户名或密码不正确！";
            }
            return Json(result);
        }

        #endregion

        #region 验证码

        /// <summary>
        /// 生成验证码图片
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult Captcha(string param)
        {
            return new CaptchaImageResult(param);
        }

        /// <summary>
        /// 检查验证码是否正确
        /// </summary>
        /// <param name="param"> </param>
        /// <param name="captcha">验证码</param>
        /// <returns></returns>
        public ActionResult CaptchaValidate(string param, string captcha)
        {
            var status = false;
            if (CaptchaKey.Contains(param))
            {
                status = CaptchaValidateInternal(param, captcha);
            }
            return Json(status, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 检查用户名

        /// <summary>
        /// 检查用户名是否已存在
        /// </summary>
        /// <param name="name">用户名/绑定邮箱/绑定手机号</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserExist(string name)
        {
            var exist = Passport.Value.UserExist(name);
            return Json(exist.Status);
        }

        /// <summary>
        /// 检查用户名是否不存在
        /// </summary>
        /// <param name="name">用户名/绑定邮箱/绑定手机号</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserNotExist(string name)
        {
            var exist = Passport.Value.UserExist(name);
            return Json(!exist.Status);
        }

        #endregion

        #region 短信验证
        /// <summary>
        /// 获取短信验证码
        /// </summary>
        /// <param name="param">分组</param>
        /// <param name="mobile">手机号</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AuthCode(int param, string mobile)
        {
            var result = new MagicKit<string>();
            var identity = User.Identity.Identity();
            if (param >= 0 && mobile.IsMobile())
            {
                if (param == 0)
                {
                    result = AuthSmsSignup(mobile);
                }
                else if (param == 1)
                {
                    result = AuthSmsMobileBind(mobile);
                }
                else if (param == 2)
                {
                    result = AuthSmsResetPassword(mobile);
                }
            }
            else
            {
                result.Message = "参数不正确！";
            }
            return Json(result);
        }

        /// <summary>
        /// 验证短信验证码
        /// </summary>
        /// <param name="param">短信验证Id</param>
        /// <param name="group">分组</param>
        /// <param name="mobile">手机号</param>
        /// <param name="code">验证码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AuthCodeValidate(string param, int group, string mobile, string code)
        {
            var auth = Extra.Value.AuthSmsGet(param, mobile, group, code);
            return Json(auth != null);
        }

        /// <summary>
        /// 注册短信验证
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        private MagicKit<string> AuthSmsSignup(string mobile)
        {
            var result = new MagicKit<string>();
            if (mobile.IsMobile())
            {
                var exist = Passport.Value.UserExist(mobile);
                //exist.Data 为用户Id
                //exist.Message 为用户Name
                if (!exist.Status)
                {
                    var auth = new AuthSms();
                    var code = AuthSms.NewCode();
                    var id = Guid.NewGuid().ToString().ToUpper();

                    auth.Id = id;
                    auth.UserId = 0;
                    auth.Group = 0;
                    auth.Mobile = mobile;
                    auth.Code = code;
                    auth.Status = false;
                    auth.CreatedBy = "sys";
                    auth.CreatedOn = DateTime.Now;
                    var status = result.Status = Extra.Value.AuthSmsCreate(auth);
                    if (status)
                    {
                        result.Data = id;
                        result.Status = true;
                        //todo 发短信

                    }
                    else
                    {
                        result.Message = "发送手机验证失败，请重试！";
                    }
                }
                else
                {
                    result.Message = "该手机号码已被使用，请换一个！";
                }
            }
            else
            {
                result.Message = "请输入正确的手机号码！";
            }
            return result;
        }

        /// <summary>
        /// 手机绑定短信验证
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        private MagicKit<string> AuthSmsMobileBind(string mobile)
        {
            var result = new MagicKit<string>();
            if (mobile.IsMobile())
            {
                var exist = Passport.Value.UserExist(mobile);
                //exist.Data 为用户Id
                //exist.Message 为用户Name
                if (!exist.Status)
                {
                    var auth = new AuthSms();
                    var code = AuthSms.NewCode();
                    var identity = User.Identity.Identity();
                    var id = Guid.NewGuid().ToString().ToUpper();

                    auth.Id = id;
                    auth.UserId = identity.Id;
                    auth.Group = 1;
                    auth.Mobile = mobile;
                    auth.Code = code;
                    auth.Status = false;
                    auth.CreatedBy = User.Identity.Name;
                    auth.CreatedOn = DateTime.Now;

                    var status = result.Status = Extra.Value.AuthSmsCreate(auth);
                    if (status)
                    {
                        result.Data = id;
                        result.Status = true;
                        //todo 发短信

                    }
                    else
                    {
                        result.Message = "发送手机验证失败，请重试！";
                    }
                }
                else
                {
                    result.Message = "该手机号码已被使用，请换一个！";
                }
            }
            else
            {
                result.Message = "请输入正确的手机号码！";
            }
            return result;
        }

        /// <summary>
        /// 密码重置短信验证
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        private MagicKit<string> AuthSmsResetPassword(string mobile)
        {
            var result = new MagicKit<string>();
            if (mobile.IsMobile())
            {
                var exist = Passport.Value.UserExist(mobile);
                //exist.Data 为用户Id
                //exist.Message 为用户Name
                if (exist.Status)
                {
                    var user = Passport.Value.UserGet(exist.Data);
                    if (user != null)
                    {
                        var auth = new AuthSms();
                        var code = AuthSms.NewCode();
                        var id = Guid.NewGuid().ToString().ToUpper();

                        auth.Id = id;
                        auth.UserId = exist.Data;
                        auth.Group = 2;
                        auth.Mobile = mobile;
                        auth.Code = code;
                        auth.Status = false;
                        auth.CreatedBy = exist.Message;
                        auth.CreatedOn = DateTime.Now;

                        var status = Extra.Value.AuthSmsCreate(auth);
                        if (status)
                        {
                            result.Data = id;
                            result.Status = true;
                            //todo 发短信
                        }
                        else
                        {
                            result.Message = "发送手机验证失败，请重试！";
                        }
                    }
                    else
                    {
                        result.Message = "用户不存在！";
                    }
                }
                else
                {
                    result.Message = "该手机号码不存在或未绑定任何帐号！";
                }
            }
            else
            {
                result.Message = "请输入正确的手机号码！";
            }
            return result;
        }

        #endregion
    }
}
